<template>
  <div id="app">
    <el-header>
      <h1>后台管理系统</h1>
    </el-header>
    <el-container>
      <el-aside :style="{ width: isAsideCollapsed ? '60px' : '200px' }">
        <div class="toggle-button" @click="toggleAside">
          <el-icon v-if="isAsideCollapsed"><DArrowRight /></el-icon>
          <el-icon v-else><DArrowLeft /></el-icon>
        </div>
        <el-menu
          default-active="/"
          mode="vertical"
          background-color="#304156"
          text-color="#fff"
          active-text-color="#ffd04b"
          @select="handleMenuSelect"
          :collapse="isAsideCollapsed"
        >
          <template v-for="menuItem in menuItemList" :key="menuItem.index">
            <el-sub-menu v-if="menuItem.children && menuItem.children.length" :index="menuItem.index">
              <template #title>
                <el-icon><component :is="menuItem.icon" /></el-icon>
                <span v-if="!isAsideCollapsed">{{ menuItem.label }}</span>
              </template>
              <el-menu-item v-for="subMenu in menuItem.children" :key="subMenu.index" :index="subMenu.index">
                <el-icon><component :is="subMenu.icon" /></el-icon>
                <span>{{ subMenu.label }}</span>
              </el-menu-item>
            </el-sub-menu>
            <el-menu-item v-else :index="menuItem.index">
              <el-icon><component :is="menuItem.icon" /></el-icon>
              <span v-if="!isAsideCollapsed">{{ menuItem.label }}</span>
            </el-menu-item>
          </template>
        </el-menu>
      </el-aside>
      <el-main>
        <el-tabs v-model="activeTab" type="card" closable @tab-remove="removeTab" @tab-click="handleTabClick">
          <el-tab-pane v-for="tab in tabs" :key="tab.name" :label="tab.label" :name="tab.name">
            <router-view :key="tab.name"></router-view>
          </el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import axios from "axios";

const router = useRouter();
const route = useRoute();
const isAsideCollapsed = ref(false);
const activeTab = ref("");
const tabs = ref<{ name: string; label: string; route: string }[]>([]);
const routeCounters = ref<Record<string, number>>({});
const menuItemList = ref<any[]>([]);

onMounted(async () => {
  try {
    const response = await axios.post("/access-control-list-server/accountMenu/selectAccountMenuList", {
      userNum: "ceo01",
      businessLine: "web",
    });
    if (response.status === 200) {
      menuItemList.value = response.data.data || [];
    }
  } catch (error) {
    console.error("获取菜单数据失败:", error);
  }
});

const handleMenuSelect = (index: string) => {
  const menuItem = findMenuItemByIndex(index);
  if (!menuItem) return;

  routeCounters.value[index] = (routeCounters.value[index] || 0) + 1;
  const tabName = `${index}-${routeCounters.value[index]}`;
  tabs.value.push({
    name: tabName,
    label: `${menuItem.label} - ${routeCounters.value[index]}`,
    route: index,
  });
  activeTab.value = tabName;
  router.push(index);
};

const findMenuItemByIndex = (index: string) => {
  for (const menuItem of menuItemList.value) {
    if (menuItem.index === index) return menuItem;
    for (const subMenuItem of menuItem.children || []) {
      if (subMenuItem.index === index) return subMenuItem;
    }
  }
  return null;
};

const handleTabClick = (tab: any) => {
  const targetTab = tabs.value.find((t) => t.name === tab.props.name);
  if (targetTab) router.push(targetTab.route);
};

const removeTab = (tabName: string) => {
  const index = tabs.value.findIndex((tab) => tab.name === tabName);
  if (index !== -1) tabs.value.splice(index, 1);
  activeTab.value = tabs.value.length ? tabs.value[tabs.value.length - 1].name : "";
  router.push(activeTab.value ? tabs.value.find((tab) => tab.name === activeTab.value)!.route : "/");
};

watch(
  () => route.path,
  (newPath) => {
    const targetTab = tabs.value.find((tab) => tab.route === newPath);
    if (targetTab) activeTab.value = targetTab.name;
  },
  { immediate: true }
);

const toggleAside = () => (isAsideCollapsed.value = !isAsideCollapsed.value);
</script>

<style scoped>
html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
#app { height: 100vh; display: flex; flex-direction: column; overflow: hidden; }
.el-header { background-color: #409eff; color: white; display: flex; align-items: center; padding: 0 20px; height: 60px; }
.el-container { flex-grow: 1; display: flex; height: calc(100vh - 60px); overflow: hidden; }
.el-aside { background-color: #304156; color: white; display: flex; flex-direction: column; transition: width 0.3s; overflow: hidden; }
.toggle-button { display: flex; justify-content: center; align-items: center; height: 50px; cursor: pointer; background-color: #263445; }
.el-menu { flex-grow: 1; border-right: none; overflow: hidden; }
.el-main { background-color: #f0f2f5; padding: 0; flex-grow: 1; overflow: hidden; }
.el-tabs { height: 100%; }
</style>
